package com.ck.client.service.impl;

import com.ck.client.dao.BindMapper;
import com.ck.client.model.vo.DeviceBindMsg;
import com.ck.client.service.BindService;
import com.ck.common.model.OperationResult;
import com.ck.core.constant.device.DeviceGroupConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 *
 */
@Service(value = "dindService")
public class BindServiceImpl implements BindService {
	private static Logger logger = LoggerFactory.getLogger(BindServiceImpl.class);

	@Autowired
	private BindMapper bindMapper;
	@Override
	public Long getStoreIdBySerialNum(String storeSerialNum) {
		return bindMapper.getStoreIdBySerialNum(storeSerialNum);
	}

	@Override
	public String getSerialNumByStoreId(Long storeId) {
		return bindMapper.getSerialNumByStoreId(storeId);
	}

	@Override
	public Boolean deviceSerialNumExisted(Long storeId, String deviceSerialNum) {
		return bindMapper.deviceSerialNumExisted(storeId,deviceSerialNum) != null;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public OperationResult bind(DeviceBindMsg bindMsg) {
		boolean result =  bindMapper.bind(bindMsg) > 0;
		logger.info(">> >> 执行最终绑定操作，绑定结果为:{}；绑定对象:{}", result,bindMsg.toString());
		OperationResult<Object> operationResult = OperationResult.newSuccessOperationResult();
		operationResult.setMsg(result ? "绑定成功" : "绑定失败，未成功入库");
		return operationResult;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean macBind(String mac, String deviceCode, String serialNum) {
		int effect = bindMapper.macBind(mac,deviceCode,serialNum);
		return effect > 0;
	}

	@Override
	public Long getStoreIdWithRecentlyIP(String ip) {
		return bindMapper.getStoreIdWithRecentlyIP(ip);
	}

	@Override
	public Boolean isDeviceCodeBinded(String deviceCode) {
		Long recordId = bindMapper.isDeviceCodeBinded(deviceCode);
		return recordId != null;
	}

	@Override
	public String generateDeviceSerialNum(Long storeId) {
		// 取当前门店下的设备数量，生成四位数字（不足补零）
		String storeSerialNum = getSerialNumByStoreId(storeId);

		// 当前门店已使用的设备序列号
		List<String> allUsedDeviceSerialNum = bindMapper.getAllUsedDeviceSerialNum(storeId);

		// 循环生成序列号
		int i = 1;
		int total = 9999;
		while ( i < total ) {
			i ++;
			String serialNum = storeSerialNum + String.format("%04d", i );
			if ( !allUsedDeviceSerialNum.contains(serialNum) ) {
				return serialNum;
			}
		}
		logger.warn("循环完毕，无法生成设备序列号！！！！");
		return null;
	}

	@Override
	public Long getStoreIdWithMac(String mac) {
		return bindMapper.getStoreIdWithMac(mac);
	}

	@Override
	public Long getDeviceGroupWithStore(String deviceCode) {
		Long getDeviceGroupWithStore = bindMapper.getDeviceGroupWithStore(deviceCode);
		return getDeviceGroupWithStore == null ? DeviceGroupConstant.NONE_DEVICE_GROUP_ID: getDeviceGroupWithStore;
	}

}
